package com.xw.loadclass;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;


/**
 * @author: xw
 * @create: 2023/4/12 14:51
 * @description: 自定义类加载器
 */
public class CustomerClassLoaderDefine extends ClassLoader{
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
//       File file = new File("D:/study/2022/msb/datastructure/out/production/jvm/",
//               name.replace(".", "/").concat(".class"));

        File file = new File("D:/test/",
                name.replace(".", "/").concat(".class"));

        try {
            int b = 0;
            FileInputStream fs = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while((b = fs.read()) != -1){
                baos.write(b);
            }
            byte[] bytes = baos.toByteArray();
            baos.close();
            fs.close();//可以写的更加严谨

            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name);

    }
    public static void main(String[] args) throws Exception {
        ClassLoader l = new CustomerClassLoaderDefine();
//        Class clazz = l.loadClass("com.xw.loadclass.HelloJVM");
        Class clazz = l.loadClass("HelloJVM");

        System.out.println(l.getClass().getClassLoader());
        System.out.println(l.getParent());
        System.out.println("-----------------------------------------");
        System.out.println("测试的字节码是由"+clazz.getClassLoader().getClass().getName());
        Object o = clazz.newInstance();
        System.out.println(o.toString());
//        HelloJVM h = (HelloJVM) clazz.newInstance();
//        h.m();

    }

}
